<template>
<div class="container">
  <el-card>
    <img class="logo" src="@/assets/images/logo.png" alt="" />
    <!-- 表单 收集和校验数据 -->
 <el-form ref="formRef" :model="form" :rules="rules">
  <el-form-item prop="mobile">
      <el-input v-model="form.mobile" placeholder="请输入账号"></el-input>
     </el-form-item>
     <el-form-item prop="password">
      <el-input v-model="form.code" placeholder="请输入验证码"></el-input>
     </el-form-item>
     <!-- 按钮 -->
     <el-form-item>
    <el-button @click="login" type="primary">登 录</el-button>
  </el-form-item>
  <el-form-item>
    <el-checkbox v-model="checked">我已阅读并同意「用户协议」和「隐私条款」</el-checkbox>
  </el-form-item>
 </el-form>

  </el-card>
</div>
</template>
<script>
import auth from '@/utils/token'
export default {
  // 组件名必须是组合词
  name: 'LoginPage',
  data () {
    const checkMobile = (rule, value, callback) => {
      // 1.rule 当前校验规则
      // 2.value表单值 校验结果
      // 3. callback校验提示
      // 4.校验回调
      // 手机号 1开头 第二位3-9 剩下九位是数字
      if (/^1[3-9]\d{9}$/.test(value)) {
        callback()
      } else {
        callback(new Error('手机号格式错误'))
      }
    }
    return {
      form: {
        mobile: '',
        code: ''
      },
      rules: {
        mobile: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          // validator 自定义校验
          { validator: checkMobile, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '验证码不能为空', trigger: 'blur' },
          { len: 6, message: '验证码长度为6位', trigger: 'blur' }
        ]
      },
      checked: false
    }
  },
  methods: {
    login () {
      // 使用ref="xxx"绑定el-form组件，使用this.$refs.xxx.validate()校验整体表单。
      // 校验整个表单
      this.$refs.formRef.validate(async (res) => {
        if (res) {
          // 校验通过
          // alert('登录成功')
          try {
            const res = await this.$http.post('/v1_0/authorizations', this.form)
            // 保存token
            // localStorage.setItem('geek-client-token', res.data.data.token)
            auth.setToken(res.data.data.token)
            // 跳转页面
            this.$router.push('/')
            // 成功提示
            this.$message.success('登录成功')
            // console.log('成功', res)
          } catch (err) {
            this.$message.error(err.response.data.message || '登录失败')
            // console.log('失败', err)
          }
        }
      })
    }
  }
}
</script>
<!-- 局部样式：添加 scoped 避免样式冲突 -->
<style lang="less" scoped>
.container {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: url('@/assets/images/login.png');
  .el-card {
    width: 440px;
    height: 380px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    box-shadow: 0 0 50px rgba(0,0,0,0.1);
    .logo {
      width: 200px;
      display: block;
      margin: 0 auto 20px;
    }
  };
  .el-form {
  padding: 0 20px;
  .el-button {
    width: 100%;
  }
}
}
</style>
